/****************************************************************
 ** Product  :   HP Subscriber Network Application Policy
 ** Module   :   gr-manager
 ** Date: Apr 10, 2015               
 ** Author: Chen Zhenhua
 ** (C) Copyright 2015, Hewlett-Packard Company, All Rights Reserved.
 ** This software is the proprietary information of HP, Inc.  
 ** Use is subject to license terms.
 *****************************************************************
 ** Description:   
 **  Remove a Linux cron job from cron job list for the GR tool
 **  
 ****************************************************************/
package com.hp.snap.gr.action.impl;

import com.hp.snap.gr.exception.ActionException;
import com.hp.snap.gr.model.jaxb.ActionType;
import com.hp.snap.gr.model.jaxb.GeneralActionType;
import com.hp.snap.gr.model.jaxb.ParameterType;
import com.hp.snap.gr.utils.CmdResult;
import com.hp.snap.gr.utils.CmdUtils;
import com.hp.snap.gr.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.LineNumberReader;
import java.io.StringReader;
import java.util.List;
import java.util.Map;

/**
 * Remove a Linux cron job from cron job list for the GR tool. You can choose to remove all GR cron job by setting the Mode to "ALL";
 *
 * There are two optional parameters configured in the action: Mode and Command.
 * Mode: Value "ALL" means delete all GR cron job;
 * Command: The GR tool command to be removed from cron tab.
 * 
 * <P>
 * Version: 3.3 <br>
 * Author: Chen Zhenhua
 * Date: Apr 10, 2015
 * 
 * </P>
 *
 **/
public class UnRegisterCronjobActionHandler extends AbstractActionHandler {

    private final static String ALL = "ALL";
    private static Logger logger = LoggerFactory.getLogger(UnRegisterCronjobActionHandler.class);

    @Override
    public void execute(ActionType action,
                        Map<String, Object> actionPlanInputs,
                        Map<String, Object> actionPlanOutputs) throws ActionException {

        GeneralActionType actionType = (GeneralActionType) action;
        List<ParameterType> parameterTypes = actionType.getParameter();
        Map<String, String> parameterMap = Utils.contructParamMap(parameterTypes);
        String mode = parameterMap.get("Mode");
        String command = parameterMap.get("Command");
        StringBuilder shellCommandBuf = new StringBuilder();
        if (ALL.equals(mode) && command == null) {
            shellCommandBuf.append("crontab -r");
        } else {
            try {
                CmdResult result = new CmdResult();
                int rs = CmdUtils.runShellScript("crontab -l", result);
                if (rs == 0) {
                    String cronJobs = result.getStdout().toString();
                    LineNumberReader r = new LineNumberReader(new StringReader(cronJobs));
                    int rowCount = 0;
                    for (String line = r.readLine(); line != null; line = r.readLine()) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("exist cron job:{}", line);
                        }
                        if (!line.endsWith(command)) {
                            shellCommandBuf.append(" echo \"").append(line).append("\" >>cron.job && ");
                            rowCount++;
                        }
                    }
                    if (rowCount == 0) shellCommandBuf.append("crontab -r && ");
                    else shellCommandBuf.append(" crontab cron.job && ");
                    shellCommandBuf.append("rm -rf cron.job");
                } else if (rs == 1) {
                    logger.warn("Do not found cron job. unRegister operation ignore!");
                    //throw new ActionException("execute 'crontab -l' command failed !!");
                }
            } catch (Exception e) {
                logger.error("handler the unregister cron job error, the exception is:{}", e.getMessage());
                throw new ActionException("handler the unregister cron job error", e.getCause());
            }
        }
        String shellCommand = shellCommandBuf.toString();
        logger.trace("unRegister cron job shell command is {}", shellCommand);
        try {
            CmdResult result = new CmdResult();
            int rs = CmdUtils.runShellScript(shellCommand, result);
            if (rs != 0) {
                logger.error("unregister the cron job failed, command is {}", command);
                throw new ActionException("unRegister cron job failed!!");
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            throw new ActionException("unRegister cron job failed!!", ex.getCause());
        }
    }

}
